package com.myl.core.utils.mail;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

/**
 * MailSender
 * author: myl <ixiaomu@qq.com>
 * Example:
 * String to = "demo@admin.com";
 * MailSendInfo dto = new MailSendInfo()
 *          .setEmail("myl@email.com")
 *          .setUsername("myl@email.com")
 *          .setPassword("12345678")
 *          .setPersonal("sysadmin")
 *          .setHost("smtp.email.com")
 *          .setPort(465)
 *          .setAuth(Boolean.TRUE)
 *          .setStarttlsEnable(Boolean.FALSE)
 *          .setToUsers(List.of(to))
 *          .setLogoUrl("");
 * String randomCode = RandomUtil.randomNumbers(6);
 * dto.setTitle("title-" + randomCode)
 *    .setContent(randomCode);
 * MailSender.send(dto);
 */
@Slf4j
@UtilityClass
public class MailSender {
    /**
     * 邮件发送
     *
     * @param dto 邮件发送信息
     */
    public void send(MailSendInfo dto) {
        log.error("[邮件发送 dto<{}>]", dto);
        try {
            MailUtil.send(getMailAccount(dto), dto.getToUsers(), dto.getTitle(), dto.getContent(), Boolean.TRUE);
            log.error("[邮件发送成功 dto<{}>]", dto);
        } catch (Exception e) {
            log.error("[邮件发送出现异常 <{}>]", e.getMessage(), e);
        }
    }

    /**
     * @param info 邮件发送信息
     * @return MailSendInfo
     */
    private MailAccount getMailAccount(MailSendInfo info) {
        MailAccount account = new MailAccount();
        account.setHost(info.getHost());
        account.setPort(info.getPort());
        account.setAuth(info.getAuth());
        account.setFrom(info.getEmail());
        if (StrUtil.isNotBlank(info.getPersonal())) {
            // Test<xxxx@xxx.com>
            account.setFrom(info.getPersonal() + "<" + info.getEmail() + ">");
        }
        if (info.getStarttlsEnable()) {
            account.setStarttlsEnable(Boolean.TRUE);
            account.setSslEnable(Boolean.FALSE);
        } else {
            account.setSslEnable(Boolean.TRUE);
        }
        account.setUser(info.getUsername());
        account.setPass(info.getPassword());
        return account;
    }
}
